$(document).ready(function(){
    function data2HTML(array, level, linee){
        var lev = level || 0; var le = linee || "\n"; var toRet = "", status="";
        if (array.length<1 && lev===0){ return "<p> No groups !</p>"};

        for (var i=0, j=array.length; i<j; i++){
            if (lev===0){ toRet = "<ul class=\"groups\">"; } else {toRet = "<ul>";};
            switch(array[i].status){
                case 0: status = "inactive"; break;
                case 1: status = "active";   break;
                case 2: status = "blocked";  break;
                default:status = "active";   break;
            }
            toRet += "<li>"+le+
                    "<a id=\""+array[i].id+"\" class=\""+status+
                    "_group\" href=\"\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Description: \n"+
                    array[i].description+"\n"+
                    "Created: "+array[i].date_created+"\n"+
                    "Status: "+status+"\">"+
                    array[i].name+"</a>"+le+
                    "</li>"+le;
            if (array[i].children.length>0){ toRet += data2HTML(array[i].children, ++lev); lev--; };
            toRet += "</ul>";
        };
        return toRet;
    };

    app.getDatafromServer({
        url:"../groupsList2JSON/",
        type:"GET",
        cache:false,
        timeout:20000
    }).done(function(data, textStatus, jqXHR){
        var ar = app.flatArray_2_nestedArray(data);
        if (ar.length<1){
            $("#glist").html("<p> No groups !</p>");
            return;
        };

        $("#glist").html(data2HTML(ar));

        $(".groups").delegate("a", "click", function(e){
            $("#input_groupParent").text(e.target.innerText.toString());
            $("#input_groupParentID").val(e.target.id);
            return false;
        });

        $(".loading-indicator").css("display","none");
        $(".panel-body").css("display", "block");
    }).fail(function(jqXHR, textStatus, errorThrown){
        $(".loading-indicator").css("display","none");
        $(".error_msg").append(textStatus+": "+JSON.stringify(errorThrown))
        $(".error_msg").css("display", "block");
    });
});
